//
//  ReportUploadImageViewController.m
//  Molian
//
//  Created by 小蚕 on 15/9/8.
//  Copyright (c) 2015年 xiaocan. All rights reserved.
//

#import "ReportUploadImageViewController.h"
#import <FSMediaPicker.h>//照片选择

@interface ReportUploadImageViewController ()<FSMediaPickerDelegate>
{
    UIImageView *headView;
}
@property (nonatomic, strong)UITextView *myTextView;
@property (nonatomic, strong)AVFile *myFile;
@end

@implementation ReportUploadImageViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.view.backgroundColor = [UIColor whiteColor];
    NSString *str;
    if (self.isComplaint) {
        str = @"投诉";
    }else{
        str = @"举报";
    }
    
    self.title = str;
    UIBarButtonItem *rightItem  = [[UIBarButtonItem alloc]initWithTitle:@"提交" style:UIBarButtonItemStylePlain target:self action:@selector(saveReport)];
    self.navigationItem.rightBarButtonItem = rightItem;
    
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(20, kNavigationBarHeight+20, 200, 20)];
    label.text = [NSString stringWithFormat:@"为什么要%@ta",str];
    label.font = kFont(15);
    label.textColor = RGBA(135, 135, 135, 1);
    [self.view addSubview:label];
    
    _myTextView = [[UITextView alloc] initWithFrame:CGRectMake(15, kNavigationBarHeight+40, DeviceWidth-30, 100)];
    _myTextView.font = kFont(15);
    _myTextView.textColor = RGBA(35, 35, 35, 1);
    _myTextView.layer.borderWidth = 0.5;
    _myTextView.layer.borderColor = [UIColor blackColor].CGColor;
    [self.view addSubview:_myTextView];
    
    UILabel *label1 = [[UILabel alloc] initWithFrame:CGRectMake(20, kNavigationBarHeight+40+100+15, 200, 20)];
    label1.text = [NSString stringWithFormat:@"上传截图"];
    label1.font = kFont(15);
    label1.textColor = RGBA(135, 135, 135, 1);
    [self.view addSubview:label1];
    
    UILabel *label2 = [[UILabel alloc] initWithFrame:CGRectMake(20, kNavigationBarHeight+40+100+15+25, DeviceWidth-40, 20)];
    label2.text = [NSString stringWithFormat:@"上传截图证据方便我们更准确的做出判断"];
    label2.font = kFont(14);
    label2.textColor = RGBA(200, 200, 200, 1);
    [self.view addSubview:label2];
    
    
    headView =[[UIImageView alloc] initWithFrame:CGRectMake(15, kNavigationBarHeight+40+100+15+25+25, 100, 100)];
    headView.layer.cornerRadius = 4;
    headView.layer.masksToBounds = YES;
    headView.userInteractionEnabled = YES;
    UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(clickImage:)];
    [headView addGestureRecognizer:tap];
     headView.image = [UIImage imageNamed:@"me_placeholder_jia_ing"];
    [self.view addSubview:headView];
    
    if(self.isComplaint){
        UILabel *label3 = [[UILabel alloc] initWithFrame:CGRectMake(20, kNavigationBarHeight+40+100+15+25+25+120, DeviceWidth-40, 60)];
        label3.numberOfLines = 0;
        label3.text = [NSString stringWithFormat:@"投诉消息会在人工审核做出处理,处理消息会适时发送给您。\n有更多意见,可以到消息-口袋君里反馈"];
        label3.font = kFont(14);
        label3.textColor = RGBA(200, 200, 200, 1);
        [self.view addSubview:label3];
    }
    // Do any additional setup after loading the view.
}
- (void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [_myTextView resignFirstResponder];
}
- (void)clickImage:(UITapGestureRecognizer *)tap
{
    FSMediaPicker *mediaPicker = [[FSMediaPicker alloc] init];
    mediaPicker.mediaType = FSMediaTypePhoto;
    mediaPicker.editMode = FSEditModeStandard;
    mediaPicker.delegate = self;
    [mediaPicker showFromView:self.view];
}
- (void)mediaPicker:(FSMediaPicker *)mediaPicker didFinishWithMediaInfo:(NSDictionary *)mediaInfo
{
    UIImage *image;
    if(mediaPicker.editMode == FSEditModeCircular){
        image = mediaInfo.editedImage;
    }else {
        image = mediaInfo.originalImage;
    }
    CGSize size = CGSizeMake(600  , 600);
    
    image = [ReportUploadImageViewController imageWithImageSimple:image scaledToSize:size];
    headView.image = image;
    float kCompressionQuality = 0.3;
    NSData *imgData = UIImageJPEGRepresentation(image, kCompressionQuality);
     self.myFile = [AVFile fileWithName:@"photo.jpg" data:imgData];
    [self.myFile saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (succeeded) {
            
        }else{
            [HUD Prompt:@"图片上传失败"];
            self.myFile = nil;
        }
    }];
    
}
+ (UIImage*)imageWithImageSimple:(UIImage*)image scaledToSize:(CGSize)newSize
{
    //    //创建一个图形上下文形象
    //    UIGraphicsBeginImageContext(newSize);
    //    // 告诉旧图片画在这个新的环境,所需的
    //    // new size
    //    [image drawInRect:CGRectMake(0,0,newSize.width,newSize.height)];
    //    //获取上下文的新形象
    //    UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
    //    // 结束上下文
    //    UIGraphicsEndImageContext();
    //    return newImage;
    CGFloat width = CGImageGetWidth(image.CGImage);
    CGFloat height = CGImageGetHeight(image.CGImage);
    
    float verticalRadio = newSize.height*1.0/height;
    float horizontalRadio = newSize.width*1.0/width;
    
    float radio = 1;
    if(verticalRadio>1 && horizontalRadio>1)
    {
        radio = verticalRadio > horizontalRadio ? horizontalRadio : verticalRadio;
    }
    else
    {
        radio = verticalRadio < horizontalRadio ? verticalRadio : horizontalRadio;
    }
    
    width = width*radio;
    height = height*radio;
    
    int xPos = (newSize.width - width)/2;
    int yPos = (newSize.height-height)/2;
    
    // 创建一个bitmap的context
    // 并把它设置成为当前正在使用的context
    UIGraphicsBeginImageContext(newSize);
    //下面4行代码可以把图片背景变为黑色
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [[UIColor blackColor] CGColor]);
    CGRect rect = CGRectMake(0.0f, 0.0f, newSize.width, newSize.height);
    CGContextFillRect(context, rect);
    
    // 绘制改变大小的图片
    [image drawInRect:CGRectMake(xPos, yPos, width, height)];
    
    // 从当前context中创建一个改变大小后的图片
    UIImage* scaledImage = UIGraphicsGetImageFromCurrentImageContext();
    
    // 使当前的context出堆栈
    UIGraphicsEndImageContext();
    
    // 返回新的改变大小后的图片
    return scaledImage;
}
- (void)saveReport
{
    
    
    if (self.isComplaint) {
        if(self.myTextView.text.length==0&&self.myFile == nil){
            [HUD Prompt:@"请输入投诉原因或者上传截图"];
            return;
        }
    }else{
        if(self.myTextView.text.length==0){
            [HUD Prompt:@"请输入举报原因"];
            return;
        }
        if(self.myFile == nil){
            [HUD Prompt:@"请上传截图"];
            return;
        }
    }
    
    
    
    if (self.isComplaint) {
        
        MLReportRecord *report =[MLReportRecord object];
        MLUser *u = [MLUser currentUser];
        report.reportee = self.reportee;
        report.reporter = u;
        report.remark = self.myTextView.text;
        report.status = MLReportRecordStatus_NORMAL;
        report.type = 1;
        report.img = self.myFile;
        [report saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [AVAnalytics event:@"投诉"]; // 通知服务器一个点击事件。
                [HUD Prompt:@"投诉成功"];
                [self.navigationController popViewControllerAnimated:YES];
                NSDictionary *params = @{@"touserId": [MLUser currentUser].objectId,@"type":@5};
                [AVCloud callFunctionInBackground:@"sendSysMsg" withParameters:params block:^(id object, NSError *error) {
                    
                }];
                NSDictionary *nparams = @{@"userId":self.reportee.objectId};
                [AVCloud callFunctionInBackground:@"complaintUser" withParameters:nparams block:^(id object, NSError *error) {
                    
                }];
            }else{
                [HUD Prompt:@"请返回后重试"];
            }
        }];
        
        
        
        
    }else{
        MLReportRecord *report =[MLReportRecord object];
        MLUser *u = [MLUser currentUser];
        report.reportee = self.reportee;
        report.reporter = u;
        report.remark = self.myTextView.text;
        report.status = MLReportRecordStatus_NORMAL;
        report.img = self.myFile;
        [report saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
            if (succeeded) {
                [AVAnalytics event:@"举报"]; // 通知服务器一个点击事件。
                [HUD Prompt:@"举报成功"];
                [self.navigationController popViewControllerAnimated:YES];
                NSDictionary *params = @{@"touserId": [MLUser currentUser].objectId,@"type":@3};
                [AVCloud callFunctionInBackground:@"sendSysMsg" withParameters:params block:^(id object, NSError *error) {
                    
                }];
                NSDictionary *nparams = @{@"userId":self.reportee.objectId};
                [AVCloud callFunctionInBackground:@"reportUser" withParameters:nparams block:^(id object, NSError *error) {
                    
                }];
            }else{
                [HUD Prompt:@"请返回后重试"];
            }
        }];
    }
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
